using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;

public class DirectionEmitter : MonoBehaviour
{
    public InputAction setProgress;
    public InputAction setCompass;
    public InputAction hit;

    public float maxProgress;
    public float mouseSensibility = 0.001f;

    public UnityEvent<Vector3> getDirection;
    public UnityEvent<float> getProgress;
    public UnityEvent getHit;
    public UnityEvent setNormal, setBlocked;
    public UnityEvent swCompass;

    private float progress;
    private bool addingProgress;

    private void Awake()
    {
        setCompass.performed += _ => swCompass?.Invoke();
        setProgress.performed += _ => addingProgress = true;
        setProgress.canceled += _ => addingProgress = false;
        hit.performed += ctx => getHit?.Invoke();
    }

    public void OnEnable()
    {
        setProgress.Enable();
        setCompass.Enable();
        hit.Enable();
    }

    private void OnDisable()
    {
        setProgress.Disable();
        setCompass.Disable();
        hit.Disable();
    }

    private void Update()
    {
        if (addingProgress)
        {
            progress = Mathf.Clamp(progress + Time.deltaTime, 0, maxProgress);
        }
        else
        {
            progress = Mathf.Clamp(progress - Time.deltaTime, 0, maxProgress);
        }
        Raycast();
        getDirection?.Invoke(transform.forward);
        getProgress?.Invoke(progress / maxProgress);
    }

    public void Raycast()
    {
        Ray sightRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
        if (Physics.Raycast(sightRay, out RaycastHit _, 10))
        {
            setBlocked?.Invoke();
        }
        else
        {
            setNormal?.Invoke();
        }
    } 
}
